package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService  //上报本人地理位置
public class BaiduServiceImpl implements BaiduApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Double str1, Double str2, String addr, Long userId) {
        //判断当前用户地理位置是否存在
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if(!exists){
            UserLocation userLocation = new UserLocation();
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUserId(userId);
            userLocation.setAddress(addr);
            userLocation.setLocation(new GeoJsonPoint(str2,str1));
            mongoTemplate.save(userLocation);
        }else {  //如果已存在就更新
            Update update = new Update();
            update.set("location",new GeoJsonPoint(str2,str1));
            update.set("address",addr);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }


    }
}
